package encrypt

import (
	"bytes"
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"io"
)

func Sha1String(name string) (string, error) {
	hash, err := Sha1(name)
	if err != nil {
		return "", err
	}
	return toString(hash), nil
}

func Sha1(name string) ([]byte, error) {
	var byteReader = bytes.NewReader([]byte(name))
	var hash = sha1.New()
	if _, err := io.Copy(hash, byteReader); err != nil {
		return nil, err
	}
	var hashByte = hash.Sum(nil)
	return hashByte, nil
}

func Sha256String(name string) (string, error) {
	hash, err := Sha256(name)
	if err != nil {
		return "", err
	}
	return toString(hash), nil
}

func Sha256(name string) ([]byte, error) {
	var byteReader = bytes.NewReader([]byte(name))
	var hash = sha256.New()
	if _, err := io.Copy(hash, byteReader); err != nil {
		return nil, err
	}
	var hashByte = hash.Sum(nil)
	return hashByte, nil
}

func Md5String(name string) (string, error) {
	hash, err := Md5(name)
	if err != nil {
		return "", err
	}
	return toString(hash), nil
}

func Md5(name string) ([]byte, error) {
	var byteReader = bytes.NewReader([]byte(name))
	var hash = md5.New()
	if _, err := io.Copy(hash, byteReader); err != nil {
		return nil, err
	}
	var hashByte = hash.Sum(nil)
	return hashByte, nil
}

func toString(h []byte) string {
	return hex.EncodeToString(h)
}

func Base64EncodeToString(s string) string {
	return base64.StdEncoding.EncodeToString([]byte(s))
}

func Base64DecodeString(s string) ([]byte, error) {
	return base64.StdEncoding.DecodeString(s)
}
